<template>
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="设备名称" clearable style="width: 200px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="设备组" prop="group_id">
          <el-select v-model="queryParams.group_id" placeholder="设备组" clearable style="width: 200px">
            <el-option v-for="item in groupOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="协议类型" prop="protocol">
          <el-select v-model="queryParams.protocol" placeholder="协议类型" clearable style="width: 200px">
            <el-option label="MQTT" value="mqtt" />
            <el-option label="HTTP" value="http" />
            <el-option label="CoAP" value="coap" />
            <el-option label="Modbus" value="modbus" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="设备状态" clearable style="width: 200px">
            <el-option label="离线" :value="0" />
            <el-option label="在线" :value="1" />
            <el-option label="故障" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-container" shadow="never">
      <template #header>
        <div class="card-header">
          <span>设备列表</span>
          <div>
            <el-button type="primary" @click="handleAdd">新增设备</el-button>
            <el-button @click="handleGroupManage">设备组管理</el-button>
          </div>
        </div>
      </template>

      <el-table v-loading="loading" :data="deviceList" border stripe style="width: 100%">
        <el-table-column type="index" width="50" label="#" align="center" />
        <el-table-column prop="name" label="设备名称" min-width="150" />
        <el-table-column prop="serial_no" label="序列号" min-width="150" />
        <el-table-column prop="protocol" label="协议类型" min-width="100" />
        <el-table-column prop="group.name" label="设备组" min-width="120" />
        <el-table-column prop="location" label="位置" min-width="150" />
        <el-table-column label="状态" width="80" align="center">
          <template #default="scope">
            <el-tag :type="statusType(scope.row.status)">{{ statusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="last_online" label="最后在线时间" min-width="150" />
        <el-table-column fixed="right" label="操作" width="220" align="center">
          <template #default="scope">
            <!-- 修复前的错误代码 -->
            <el-button type="primary" link size="small" @click="handleData(scope.row)">数据</el-button>
            <el-button type="success" link size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" link size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        v-if="total > 0"
        :total="total"
        v-model:currentPage="queryParams.page"
        v-model:page-size="queryParams.pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 50, 100]"
        style="margin-top: 20px; justify-content: flex-end"
      />
    </el-card>

    <!-- 设备表单对话框 -->
    <el-dialog
      :title="formTitle"
      v-model="dialogFormVisible"
      width="600px"
      @close="resetForm"
    >
      <el-form ref="deviceFormRef" :model="deviceForm" :rules="rules" label-width="100px">
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="deviceForm.name" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="序列号" prop="serial_no">
          <el-input v-model="deviceForm.serial_no" placeholder="请输入设备序列号" :disabled="formType === 'edit'" />
        </el-form-item>
        <el-form-item label="协议类型" prop="protocol">
          <el-select v-model="deviceForm.protocol" placeholder="请选择协议类型" style="width: 100%">
            <el-option label="MQTT" value="mqtt" />
            <el-option label="HTTP" value="http" />
            <el-option label="CoAP" value="coap" />
            <el-option label="Modbus" value="modbus" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备组" prop="group_id">
          <el-select v-model="deviceForm.group_id" placeholder="请选择设备组" clearable style="width: 100%">
            <el-option v-for="item in groupOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备型号" prop="model">
          <el-input v-model="deviceForm.model" placeholder="请输入设备型号" />
        </el-form-item>
        <el-form-item label="位置" prop="location">
          <el-input v-model="deviceForm.location" placeholder="请输入设备位置" />
        </el-form-item>
        <el-form-item label="经纬度">
          <div style="display: flex;">
            <el-input v-model="deviceForm.longitude" placeholder="经度" style="margin-right: 10px" />
            <el-input v-model="deviceForm.latitude" placeholder="纬度" />
          </div>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="deviceForm.status" placeholder="请选择设备状态" style="width: 100%">
            <el-option label="离线" :value="0" />
            <el-option label="在线" :value="1" />
            <el-option label="故障" :value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { getDeviceList, addDevice, editDevice, deleteDevice, getDeviceGroupList } from '@/api/device'

const router = useRouter()

// 查询参数
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  name: '',
  group_id: '',
  protocol: '',
  status: ''
})

// 设备列表数据
const deviceList = ref([])
const loading = ref(false)
const total = ref(0)

// 设备组选项
const groupOptions = ref([])

// 加载设备组选项
const loadGroupOptions = async () => {
  try {
    const res = await getDeviceGroupList()
    groupOptions.value = res.data.data
  } catch (error) {
    console.error('获取设备组失败', error)
  }
}

// 查询设备列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getDeviceList(queryParams)
    deviceList.value = res.data.data
    total.value = res.data.total
  } catch (error) {
    console.error('获取设备列表失败', error)
  } finally {
    loading.value = false
  }
}

// 设备表单相关
const dialogFormVisible = ref(false)
const deviceFormRef = ref(null)
const formType = ref('add') // add 或 edit
const formTitle = computed(() => formType.value === 'add' ? '新增设备' : '编辑设备')

// 设备表单数据
const deviceForm = reactive({
  id: undefined,
  name: '',
  serial_no: '',
  protocol: '',
  model: '',
  location: '',
  latitude: '',
  longitude: '',
  group_id: '',
  status: 0
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
  serial_no: [{ required: true, message: '请输入设备序列号', trigger: 'blur' }],
  protocol: [{ required: true, message: '请选择协议类型', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 状态文本和类型
const statusText = (status) => {
  const statusMap = {
    0: '离线',
    1: '在线',
    2: '故障'
  }
  return statusMap[status] || '未知'
}

const statusType = (status) => {
  const typeMap = {
    0: 'info',
    1: 'success',
    2: 'danger'
  }
  return typeMap[status] || ''
}

// 查询操作
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryParams.name = ''
  queryParams.group_id = ''
  queryParams.protocol = ''
  queryParams.status = ''
  handleQuery()
}

// 分页处理
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getList()
}

const handleCurrentChange = (page) => {
  queryParams.page = page
  getList()
}

// 重置表单
const resetForm = () => {
  if (deviceFormRef.value) {
    deviceFormRef.value.resetFields()
  }
  Object.assign(deviceForm, {
    id: undefined,
    name: '',
    serial_no: '',
    protocol: '',
    model: '',
    location: '',
    latitude: '',
    longitude: '',
    group_id: '',
    status: 0
  })
}

// 新增设备
const handleAdd = () => {
  resetForm()
  formType.value = 'add'
  dialogFormVisible.value = true
}

// 编辑设备
const handleEdit = (row) => {
  resetForm()
  formType.value = 'edit'
  Object.assign(deviceForm, { ...row })
  dialogFormVisible.value = true
}

// 删除设备
const handleDelete = (row) => {
  ElMessageBox.confirm(`是否确认删除设备：${row.name}？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteDevice(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除设备失败', error)
    }
  }).catch(() => {})
}

// 查看设备数据
const handleData = (row) => {
  router.push({ path: `/device/data/${row.id}`, query: { name: row.name } })
}

// 设备组管理
const handleGroupManage = () => {
  router.push({ path: '/device/group' })
}

// 提交表单
const submitForm = () => {
  deviceFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (formType.value === 'add') {
          await addDevice(deviceForm)
          ElMessage.success('添加成功')
        } else {
          await editDevice(deviceForm)
          ElMessage.success('更新成功')
        }
        dialogFormVisible.value = false
        getList()
      } catch (error) {
        console.error('保存设备失败', error)
      }
    }
  })
}

onMounted(() => {
  getList()
  loadGroupOptions()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.table-container {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-card__header) {
  padding: 10px 20px;
}

:deep(.el-dialog__body) {
  padding-top: 10px;
  padding-bottom: 10px;
}
</style> 